<template>
  <div class="container">
    <el-card class="box-card">
      <!-- 面包屑导航 -->
      <el-breadcrumb v-if="subjectName" separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>学科管理</el-breadcrumb-item>
        <el-breadcrumb-item>
          <strong>{{subjectName}}</strong>
        </el-breadcrumb-item>
        <el-breadcrumb-item>目录管理</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 搜索区 -->
      <el-row>
        <el-form ref="searchForm" :model="queryInfo" size="small" label-width="80px">
          <el-col :span="6">
            <div class="grid-content">
              <el-form-item label="目录名称">
                <el-input v-model="queryInfo.keyword"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="13">
            <div class="grid-content">
              <el-form-item label="状态">
                <el-select v-model="queryInfo.state" placeholder="请选择状态">
                  <el-option label="启用" value="1"></el-option>
                  <el-option label="禁用" value="0"></el-option>
                </el-select>
                <el-button size="small" @click="reset">清除</el-button>
                <el-button size="small" @click="loadDirectoryList" type="primary">搜索</el-button>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="5" style="text-align: right;">
            <div class="grid-content">
              <el-link
                @click="$router.back()"
                type="primary"
                v-if="subjectName"
                :underline="false"
              >⬅返回学科</el-link>
              <el-button @click="addClick" type="success" size="small" icon="el-icon-edit">新增目录</el-button>
            </div>
          </el-col>
        </el-form>
      </el-row>

      <!-- 消息提示文案 -->
      <el-alert :title="`数据一共${total}条`" :closable="false" type="info" show-icon></el-alert>

      <!-- 表格区 -->
      <el-table :data="list" stripe style="width: 100%">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="subjectName" label="所属学科" width="110px"></el-table-column>
        <el-table-column prop="directoryName" label="目录名称" width="110px"></el-table-column>
        <el-table-column prop="username" label="创建者" width="110px"></el-table-column>
        <el-table-column label="创建日期" width="160px">
          <template slot-scope="scope">{{scope.row.addDate | formatDate}}</template>
        </el-table-column>
        <el-table-column prop="totals" label="面试题数量" width="110px"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">{{scope.row.state===1?'已启用':'未启用'}}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link
              type="primary"
              :underline="false"
              @click="changeStateHandle(scope.row)"
            >{{scope.row.state===1?'禁用':'启用'}}</el-link>&nbsp;
            <el-link
              :type="!scope.row.state?'primary':'info'"
              :underline="false"
              :disabled="!!scope.row.state"
              @click="updateClick(scope.row)"
            >修改</el-link>&nbsp;
            <el-link
              :type="!scope.row.state?'primary':'info'"
              :underline="false"
              :disabled="!!scope.row.state"
              @click="deleteDirectoryHandle(scope.row)"
            >删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination
        class="pagenation"
        :queryInfo="queryInfo"
        :total="total"
        @pagination="loadDirectoryList"
      />
    </el-card>

    <!-- 新增目录对话框 -->
    <el-dialog @close="addDialogClose" :title="title" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <!-- 从菜单进入时，需要选择学科 -->
        <!-- 从学科分类进入不用选择，默认当前学科 -->
        <el-form-item v-if="!id" label="所属学科：">
          <el-select v-model="addForm.subjectID" placeholder="请选择所属学科">
            <el-option
              v-for="item in subjects"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称：" prop="directoryName">
          <el-input v-model="addForm.directoryName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="confirmHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  list as getDirectoryList,
  add as addDirectory,
  detail as getDirectoryById,
  update as updateDirectory,
  remove as removeDirectoryById,
  changeState as changeDirectoryState
} from '@/api/hmmm/directorys'
import Pagination from '@/components/Pagination'
import { simple as getSubjectsList } from '@/api/hmmm/subjects'
export default {
  name: 'Directorys',
  data() {
    return {
      // 目录列表的请求参数对象
      queryInfo: {
        keyword: '', // 目录名
        state: null, // 状态
        page: 1,
        pagesize: 10
      },
      // 目录总条数
      total: 0,
      // 目录数据列表
      list: [],
      // 新增目录 / 修改目录对话框的显示
      addDialogVisible: false,
      // 对话框标题
      title: '',
      // 添加目录的数据对象 / 修改目录的数据对象
      addForm: {
        subjectID: null,
        directoryName: ''
      },
      // 添加目录的表单验证对象
      addFormRules: {
        directoryName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }]
      },
      // 学科数组
      subjects: [],
      // 当前目录的数据Id
      dataId: null
    }
  },

  methods: {
    // 获取目录列表
    async loadDirectoryList() {
      try {
        // 处理请求参数
        const params = {
          directoryName: this.queryInfo.keyword, // 目录名
          state: null, // 状态
          page: this.queryInfo.page,
          pagesize: this.queryInfo.pagesize,
          subjectID: Number(this.id) || null // 从学科进来的传学科id，从菜单进则不传
        }
        // 发送获取数据列表请求
        const { data } = await getDirectoryList(params)
        this.list = data.items
        this.total = data.counts
      } catch (error) {
        this.$message.error('获取目录列表失败')
      }
    },

    // 清空输入框
    reset() {
      // 重新获取列表
      this.queryInfo.keyword = ''
      this.queryInfo.state = null
      this.loadDirectoryList()
    },

    // 获取学科数据
    async getSubjects() {
      try {
        // 获取所有学科数据
        const { data } = await getSubjectsList()
        this.subjects = data
      } catch (error) {
        this.$message.error('学科数据获取失败')
      }
    },

    // 点击新增目录显示对话框
    addClick() {
      this.addDialogVisible = true
      this.title = '新增目录'

      // 获取学科
      this.getSubjects()
    },

    // 点击修改显示对话框
    async updateClick(directory) {
      this.addDialogVisible = true
      this.title = '修改目录'

      try {
        // 根据id 获取当前目录详情
        const { data } = await getDirectoryById(directory)

        // 将获取的数据展示到修改对话框
        this.addForm.directoryName = data.directoryName
        this.dataId = directory.id

        // 如果需要选择学科，也将原始选择的学科渲染出来
        if (!this.id) {
          this.addForm.subjectID = data.subjectID
        }
      } catch (error) {
        this.$message.error('当前目录数据获取失败')
      }

      // 获取学科数据
      this.getSubjects()
    },

    // 关闭新增/修改目录对话框的事件
    addDialogClose() {
      // 重置选择框和输入框
      this.addForm.subjectID = null
      this.$refs.addFormRef.resetFields()
      this.subjects = []
    },

    // 点击确认添加目录 / 确认修改目录
    confirmHandle() {
      // 如果需要选择学科，验证是否选择了
      if (!this.id && this.addForm.subjectID === null) {
        return this.$message.error('请选择所属学科')
      }
      // 表单预校验
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return

        // 验证成功，判断是添加目录还是修改目录
        if (this.title === '新增目录') {
          this.addDirectoryHandle()
        } else {
          this.updateDirectoryHandle()
        }
      })
    },

    // 添加目录
    async addDirectoryHandle() {
      try {
        // 发送添加请求
        const { data } = await addDirectory({
          // 如果从学科进入，使用当前学科id
          // 如果从菜单进入，使用选择的学科id
          subjectID: this.id || this.addForm.subjectID,
          directoryName: this.addForm.directoryName
        })

        this.$message.success('添加目录成功')
        // 更新页面
        this.loadDirectoryList()
        this.addDialogVisible = false
      } catch (error) {
        this.$message.error('添加目录失败')
      }
    },

    // 修改目录
    async updateDirectoryHandle() {
      try {
        const { data } = await updateDirectory({
          // 数据id
          id: this.dataId,
          // 如果从学科进入，使用当前学科id
          // 如果从菜单进入，使用选择的学科id
          subjectID: this.id || this.addForm.subjectID,
          directoryName: this.addForm.directoryName
        })
        console.log(data)
        this.$message.success('修改目录成功')
        this.addDialogVisible = false
        this.dataId = null
        this.loadDirectoryList()
      } catch (error) {
        this.$message.error('修改目录失败')
      }
    },

    // 删除目录
    async deleteDirectoryHandle(directory) {
      const result = await this.$confirm('此操作将永久删除该目录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      if (result !== 'confirm') {
        return this.$message('您已取消了删除操作')
      }

      // 发送删除请求
      try {
        const { data } = await removeDirectoryById(directory)
        this.$message.success('删除成功')

        // 更新视图
        this.loadDirectoryList()
      } catch (error) {
        this.$message.error('删除失败，请稍后再试')
      }
    },

    // 切换启用状态
    async changeStateHandle(directory) {
      try {
        directory.state = directory.state === 1 ? 0 : 1
        const { data } = await changeDirectoryState(directory)
        this.$message.success('状态更改成功')
      } catch (error) {
        this.$message.error('状态更改失败')
      }
    }
  },

  created() {
    this.loadDirectoryList()
  },

  computed: {
    // 获取url中的查询参数
    // 学科Id
    id() {
      return this.$route.query.id
    },
    // 学科名
    subjectName() {
      return this.$route.query.name
    }
  },

  // 监听url中请求参数的改变，从学科进再从菜单进就会重新获取列表
  watch: {
    '$route.query.id': function () {
      this.loadDirectoryList()
    }
  },

  components: {
    Pagination
  }
}
</script>

<style scoped lang='scss'>
.container {
  .el-breadcrumb {
    padding-bottom: 15px !important;
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
  }
  .el-button {
    margin-left: 10px;
  }
  .el-card {
    margin: 10px 15px !important;
  }
  .el-link {
    margin: 0 5px;
  }
  .pagenation {
    float: right;
    margin: 15px 0;
  }
}
</style>
